/**
 * Created by dale on 2017/7/25.
 */
$(document).ready(function () {
    var List = [];
    var url='';
    var FileUrl='';
    var clickFlag=false;
    var form=$('#form');

    var $type=addressUri.getParam('type');
    var $id=addressUri.getParam('id');
    
    
    form.append('<input style="display: none" name="iCUId" value="'+$id+'"  />');
    form.append('<input style="display: none" name="iTrackType" value="'+$type+'"  />');
    $('body').css('background-color','#f9f9f9');
    if($type!=2){
        $(".form_datetime").datetimepicker({format: 'yyyy-mm-dd',language: 'zh-CN',minView: "month", autoclose:true});
        $('[name$="tTrackTime"]').val(new Date().format('yyyy-MM-dd'));
    }else if($type==2) {
        $(".form-date").datetimepicker({format: 'yyyy-mm-dd',language: 'zh-CN',minView: "month", autoclose:true});
        var len=$('[name^=tTime-]').length;
        $('[name^=tTime-]').each(function (i,dom) {
            $id=$(this).attr("name").split("tTime-")[1];
            if(i == len - 1||i == len-2){
                return false;
            }
            if($id%2==1){
                $(this).css('margin-bottom','15px');
            }
        });
    }
    
    $(function () {//初始化枚举
        if($type==2){
            var sYear=$("[name$='sYear']");
            sYear.append('<option value="" style="display: none" selected>请选择</option>');
            for(var i=new Date().getFullYear();i>2000;i--){
                sYear.append('<option value="'+i+'">'+i+'</option>');
            }
        }
        $('#bt_modal_confirm',parent.document).addClass('disabled');
        form.initeValidate($('#bt_modal_confirm',parent.document));
    });

    //验证

    $("#fileInput").fileinput('destroy');
    fileInput.initFileInput('fileInput',baseUrl+'customer/ajaxTest?id='+$id);
    var count=0; //记录上传次数
    $("#fileInput").on("fileuploaded", function (event, data, previewId, index) {
        count++;
        List.push({ FileName: data.response.fileName, KeyID: previewId,url:data.response.url })
        if(clickFlag&&(count==data.files.length)){
            clickFlag=false;
            count=0;
            save();
        }
    });

    $("#fileInput").on("filesuccessremove", function (event, data, previewId, index) {
        for (var i = 0; i < List.length; i++) {
            if (List[i].KeyID== data) {
                List.splice(i,1);
            }
        }
    });

    $('#bt_modal_confirm',parent.document).click(function () {
        if ($('[class=file-preview-thumbnails] [id^=preview] ')[0]!=undefined){//有文件且文件未上传
            var isUploaded=true;
            $('[class=file-preview-thumbnails] [id^=preview]').each(function () {
                if(!$(this).hasClass('file-preview-success')&&!$(this).hasClass('file-preview-error')){
                    isUploaded=false;
                }
            });
            if(isUploaded){//文件已上传
                save();
            }else {
                clickFlag=true;
                $("#fileInput").fileinput('upload');
            }
        }else {
            save();
        }

    });

    function save() {
        for (var i = 0; i < List.length; i++) {
            var footerfix= List[i]['url'].split('.')[1];
            footerfix=footerfix.toLowerCase()
            if(footerfix=='jpg'||footerfix=='gif'||footerfix=='png') {  //这里的url只指图片
                url += List[i]['url'] + ',';
            }else {
                FileUrl+=List[i]['url']+',';
            }
        }
        $('#sImages').val(url);
        $('#sFiles').val(FileUrl);
        //var timeWraper=$('#timeWraper',window.top.xhTop.getActiveFrame().frames['operationGradeTrace'].document);
        new xhForm($('#form')).submit('customer/saveTraceData',{},function (data) {
            if($type==1){
                window.top.xhTop.getActiveFrame().frames['customer']['followUpTrace'].location.reload();
            }else if($type==2){
                window.top.xhTop.getActiveFrame().frames['customer']['intentionTrace'].location.reload();
            }else {
                window.top.xhTop.getActiveFrame().frames['customer']['operationGradeTrace'].location.reload();
            }
            window.top.xhTop.closeModal();
            url='';
            FileUrl='';
            List=[];
        });
        // $.ajax({
        //     url : baseUrl+'customer/saveTraceData',
        //     data:$("#form").serialize(),
        //     dataType:'json',
        //     type:'post',
        //     success:function (data) {
        //         if(data=='fail'){
        //             alert('内容重复');
        //             return false;
        //         }
        //         if($type==1){
        //             window.top.xhTop.getActiveFrame().frames['customer']['followUpTrace'].location.reload();
        //         }else if($type==2){
        //             window.top.xhTop.getActiveFrame().frames['customer']['intentionTrace'].location.reload();
        //         }else {
        //             window.top.xhTop.getActiveFrame().frames['customer']['operationGradeTrace'].location.reload();
        //         }
        //         window.top.xhTop.closeModal();
        //         //清空
        //         url='';
        //         FileUrl='';
        //         List=[];
        //     },
        //     error:function (result) {
        //         console.log(result);
        //     }
        // });
    }


    modalBind.bindClick();
    
});